/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        int ans = 0;
        ListNode* p = head;
        while (p) {
            ans++;
            p = p->next;
        }
        if (ans == 1 && n == 1)return nullptr;
        ans -= n;
        if (!ans) {
            return head->next;
        }
        p = head;
        ListNode* pre;
        while (ans--) {
            pre = p;
            p = p->next;
        }
        pre->next = p->next;
        return head;
    }
};